package imagedecode

import (
	"bytes"
	"errors"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"io/ioutil"
	"os"
)

var GIF = []byte("GIF")
var BMP = []byte("BM")
var JPG = []byte{0xff, 0xd8, 0xff}
var PNG = []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a}

const (
	GIF_TYPE = "image/gif"
	BMP_TYPE = "image/x-ms-bmp"
	JPG_TYPE = "image/jpeg"
	PNG_TYPE = "image/png"
)

func Decode(imgName string) (image.Image, error) {
	i, ee := os.Open(imgName)

	defer i.Close()
	if ee != nil {
		return nil, ee
	}
	it, e := GetImageType(imgName)
	if e != nil {
		return nil, e
	}
	switch it {
	case GIF_TYPE:
		return gif.Decode(i)
	case JPG_TYPE:
		return jpeg.Decode(i)
	case PNG_TYPE:
		return png.Decode(i)
	default:
		return nil, errors.New("undefined type")
	}
}

func GetImageType(imgName string) (string, error) {
	fi, e := ioutil.ReadFile(imgName)
	if e != nil {
		panic(e)
	}
	var itype string
	if bytes.Equal(PNG, fi[0:8]) {
		itype = PNG_TYPE
	}
	if bytes.Equal(GIF, fi[0:3]) {
		itype = GIF_TYPE
	}
	if bytes.Equal(BMP, fi[0:2]) {
		itype = BMP_TYPE
	}
	if bytes.Equal(JPG, fi[0:3]) {
		itype = JPG_TYPE
	}

	if itype == "" {
		return itype, errors.New("undefined type")
	} else {
		return itype, nil
	}
}
